import { ref, Ref, unref } from "vue";

// 仅支持10进制，NAN和Infinity 不合法
import Big from "big.js";
import { isNumber } from "@tarojs/shared";

type TCounterOptions = {
  min?: number;
  max?: number;

  precision?: number;
};

const useCounter = (
  initialval?: number | Ref<number | undefined>,
  options: TCounterOptions = {}
) => {
  const { max, min, precision } = options;

  const _initialVal = unref(initialval);

  const count = ref(initialval);

  // 步长
  const step = isNumber(precision) ? Math.pow(10, precision) : 1;

  // increment:增量
  const inc = () => {
    const val = count.value ?? 0;
    set(Big(val).plus(step));
  };

  // decrement  递减
  const dec = () => {
    const val = count.value ?? 0;
    set(Big(val).minus(step));
  };

  // 设置值
  const set = (val: number) => {

  
    if (isNumber(val)) {
      val = Number(isNumber(precision) ? val.toFixed(precision) : val);
      val = isNumber(max) ? Math.min(max, val) : val;
      val = isNumber(min) ? Math.max(min, val) : val;
    }
    count.value = val;
  };

  // 重置
  const reset = () => {
    count.value = _initialVal;
  };

  return {
    count,
    inc,
    dec,
    set,
    reset,
  };
};

export default useCounter;
